package com.asen.commons.core.web;

import com.asen.commons.core.base.ResultCode;
import com.asen.commons.core.base.enums.ResultTypeEnum;
import com.asen.commons.exception.RemoteException;
import com.asen.commons.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * 错误响应消息
 *
 * @author Gary
 * @version 1.0
 * @date 2020-02-25
 */
@Data
@NoArgsConstructor
@ApiModel("异常响应")
public class ErrorResponse {

    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    @ApiModelProperty("时间")
    private Date timestamp;

    @ApiModelProperty("状态码")
    private Integer status;

    @ApiModelProperty("错误")
    private String error;

    @ApiModelProperty("错误信息")
    private String message;

    @ApiModelProperty("异常类名")
    private String exception;

    @ApiModelProperty("错误类型")
    private ResultTypeEnum errorType;

    @ApiModelProperty("错误码")
    private ResultCode errorCode;

    @ApiModelProperty("详细信息")
    private String detail;

    @ApiModelProperty("异常堆栈")
    private Throwable trace;

    @ApiModelProperty("路径")
    private String path;

    /**
     * 转换为exception对象
     *
     * @return
     */
    public RemoteException toException() {
        return toException(null, null);
    }

    public RemoteException toException(String message, String detail) {
        message = StringUtils.defaultString(message, this.getMessage());
        detail = StringUtils.defaultString(detail, this.getDetail());
        RemoteException exception = new RemoteException(message, detail, this.getTrace());
        exception.setType(this.getErrorType());
        exception.setCode(this.getErrorCode());
        exception.setDetail(this.getDetail());
        exception.setPath(this.getPath());
        exception.setTimestamp(this.getTimestamp());
        exception.setStatus(this.getStatus());
        return exception;
    }
}
